﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ROToolBelt.IO.GRF
{
    public class FileEntryReader : GrfBinaryReader
    {
        public FileEntryReader(Stream input)
            : base(input)
        {
        }

        public FileEntry ReadFileEntry()
        {
            FileEntry fileEntry = new FileEntry();
            fileEntry.Path = this.ReadString();
            fileEntry.CompressedLength = this.ReadInt32();
            fileEntry.CompressedLengthAlligned = this.ReadInt32();
            fileEntry.UncompressedLength = this.ReadInt32();
            fileEntry.Flag = this.ReadByte();
            fileEntry.Offset = this.ReadInt32() + GrfHeader.GRF_HEADER_SIZE;

            if (fileEntry.Flag == 3 || fileEntry.Flag == 5)
            {
                int digits;
                int cycle;
                int i;

                // compute number of digits of the entry length
                digits = 1;
                for (i = 10; i <= fileEntry.CompressedLength; i *= 10)
                    ++digits;

                // choose size of gap between two encrypted blocks
                // digits:  0  1  2  3  4  5  6  7  8  9 ...
                //  cycle:  1  1  1  4  5 14 15 22 23 24 ...
                cycle = (digits < 3) ? 1
                      : (digits < 5) ? digits + 1
                      : (digits < 7) ? digits + 9
                      : digits + 15;

                fileEntry.Cycle = cycle;
            }

            return fileEntry;
        }
    }
}
